﻿using System.IO;
using System.Reflection;
using MassTransit;
using MassTransitDemo.TrackingService.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace MassTransitDemo.TrackingService
{
    class Program
    {
        static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        static IHostBuilder CreateHostBuilder(string[] args)
        {
            var build = new HostBuilder();
            build.ConfigureServices((hostContext, services) =>
            {
                var configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json")
                    .Build();

                services.AddMassTransit(cfg =>
                {
                    cfg.AddSagaStateMachine<RoutingSlipStateMachine, RoutingSlipState>()
                        .EntityFrameworkRepository(r =>
                        {
                            r.AddDbContext<DbContext, RoutingSlipStateDbContext>((provider, builder) =>
                            {
                                builder.UseMySql(configuration.GetConnectionString("Default"), MySqlServerVersion.LatestSupportedServerVersion, m =>
                                {
                                    m.MigrationsAssembly(Assembly.GetExecutingAssembly().GetName().Name);
                                    m.MigrationsHistoryTable($"__{nameof(RoutingSlipStateDbContext)}");
                                });
                            });
                        });
                });

                services.AddHostedService<ResponseHostedService>();
            });

            return build;
        }
    }
}
